package com.ima.controller;

import com.alibaba.fastjson.JSON;
import com.ima.common.repository.utils.DynamicSpecifications;
import com.ima.common.repository.utils.OP;
import com.ima.common.repository.utils.SearchFilter;
import com.ima.dto.DTO;
import com.ima.model.IDouChange;
import com.ima.model.IDouChange_;
import com.ima.service.IAiDouService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 用户各种操作接口
 * Created by 符柱成 on 17-3-11.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IAiDouService iAiDouService;

    @RequestMapping(value = "/test", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html;charset=UTF-8")
    public String test(String type, Integer iDouCount ) throws Exception {
        DTO dto = new DTO();
        /*IDouChange iDouChange = new IDouChange();
        iDouChange.setChangeType(type);
        iDouChange.setiDouCount(iDouCount);*/
        List<IDouChange> all = iAiDouService.findAll();
        IDouChange iDouChange = all.get(0);
        iDouChange.setChangeType("33333333333");
//        iAiDouService.update(iDouChange);
//        aiDouChangeRepository.save(iDouChange);
        Collection<SearchFilter> filters = Arrays.asList(
                new SearchFilter(IDouChange_.changeType.getName(), OP.EQ, "abc")
        );
        Specification<IDouChange> objectSpecification = DynamicSpecifications.bySearchFilter(filters);
        List<IDouChange> all1 = iAiDouService.findAll(filters);
//        iAiDouService.findAll(Specifications<IDouChange>.spec);
        if (iDouChange == null) {
            dto.code = "-1";
            dto.msg = "Have bean registered";
            return JSON.toJSONString(dto);
        } else {
            return JSON.toJSONString(all1);
        }
    }

    @RequestMapping(value = "/test2")
    public String list(Model model, Pageable pageable, ServletRequest request) throws Exception {
        List<SearchFilter> filters = SearchFilter.parse(request);
        filters.add(new SearchFilter("changeType", OP.EQ, "abc"));
        Specification<IDouChange> objectSpecification = DynamicSpecifications.bySearchFilter(filters);
        pageable = new PageRequest(0,3, Sort.Direction.DESC,"id");
        Page<IDouChange> all = iAiDouService.findAll(objectSpecification, pageable);
        return JSON.toJSONString(all.getContent());
    }

}
